import { C33ShoppingCart, Layout } from "@/components";
import {
  getUserCart,
  placeOrder,
  removeUserCart,
  useUserInfo,
} from "@/store/userDataContext";
import { useAuth } from "@/store/authContext";
import { useEffect, useState } from "react";
import { ApiItemTypeMapping } from "@/data/shared/entityShapes";
import { useDidShow } from "@tarojs/taro";
import { navigateTo } from "@/utils/navigation";
import style from "./index.module.scss";
import { ActionKeys, ActionNames, sendAction } from "@/utils/tracking";

function Cart() {
  const { userInfoState, dispatchUserDataAction } = useUserInfo();
  const { userData, selectedCartData } = userInfoState;
  const [cart, setCart] = useState<Array<any>>([]);
  const { dispatchAuthAction } = useAuth();

  useDidShow(() => {
    getUserCart(dispatchUserDataAction, userData!, {
      query: { isValid: 2, limit: process.env.defaultPageSize!, page: 1 },
      authDispatch: dispatchAuthAction,
    });
    sendAction(ActionNames.ShoppingCartImpression, null);
  });

  useEffect(() => {
    if (userData?.cart) {
      setCart(userData!.cart!);
    }
  }, [userData?.cart]);

  const removeCallback = async (ids, i) => {
    if (userData) {
      const removed = await removeUserCart(dispatchUserDataAction, userData, {
        query: { ids: ids },
        authDispatch: dispatchAuthAction,
      });
      if (removed) {
        const newCart = cart.filter((ni: any, index: number) => {
          return index !== i;
        });
        setCart(newCart);
      } else {
        return;
      }
    }
  };

  const handlePlaceOrder = async () => {
    if (selectedCartData && selectedCartData?.length > 0) {
      const newCartItems = cart.filter((ci: any) => {
        return selectedCartData.some((f) => {
          return ci.quantity && ci.availability !== 0 && ci.id === f;
        });
      });
      const cartItems = Object.values(newCartItems).map((ci: any) => {
        return {
          count: ci.quantity,
          attrValueId: ci.attrId,
          productId: ci.productId,
          shoppingCartId: ci.id,
        };
      });
      const preOrderNo = await placeOrder({
        query: {
          type: ApiItemTypeMapping.ShopItem,
          orderDetails: cartItems,
          preOrderType: "shoppingCart",
        },
        authDispatch: dispatchAuthAction,
      });
      const productDetailSkuAttr = newCartItems.map((pd) => {
        return {
          [ActionKeys.SkuType]: pd.categoryName,
          [ActionKeys.SkuName]: pd.name,
          [ActionKeys.SkuNumber]: pd.quantity.toString(),
          [ActionKeys.SkuAmount]: pd.unitPrice.toString(),
        };
      });
      sendAction(ActionNames.ShoppingCartSubmitClick, {
        [ActionKeys.SkuAttribute]: productDetailSkuAttr,
        [ActionKeys.TotalAmount]: newCartItems.reduce(
          (sum, cartItem) => sum + cartItem.quantity * cartItem.unitPrice
        ),
      });
      if (preOrderNo) {
        navigateTo(`pages/checkout/index?preOrderNo=${preOrderNo}`);
      }
    }
  };

  return (
    <Layout>
      {cart && (
        <C33ShoppingCart
          cartItems={cart}
          removeCallback={removeCallback}
          handleSubmit={handlePlaceOrder}
        />
      )}
    </Layout>
  );
}

export default Cart;
